<!--
* @FileDescription: 选择部门
* @Author: zhangjing
* @Date: 2021-9-28 3:27:32 ?F10: PM?
* @LastEditors: zhangjing
* @LastEditTime: 2021-9-28 3:27:32 ?F10: PM?
 -->
<template>
	<globalModal :title="title" :visible="visible" :confirmLoading="confirmLoading" @ok="handleOk" @cancel="handleCancel">
		<a-spin :spinning="confirmLoading" style="min-height: 400px;">
			<div class="flex">
				<a-input-search class="flex-1" placeholder="筛选部门" @change="searchDept" allow-clear />
				<a-button type="primary" class="ml10" @click="getDeptTree">刷新部门</a-button>
			</div>
			<a-tree
				class="mt10"
				:tree-data="treeData"
				:expanded-keys="expandedKeys"
				:auto-expand-parent="autoExpandParent"
				@expand="onExpand"
				:replaceFields="replaceFields"
				:selectedKeys.sync="treeKeys"
				@select="selectTree"
				:multiple="mode == 'multiple'"
			>
				<template slot="title" slot-scope="{ deptName, deptType }">
					<img class="icon" src="../assets/img/other-icon.png" v-if="deptType == 'OTHER'" />
					<img class="icon" src="../assets/img/farm.png" v-if="deptType == 'FARM'" />
					<span v-if="deptName.indexOf(searchValue) > -1">
						{{ deptName.substr(0, deptName.indexOf(searchValue)) }}
						<span style="color: #f50">{{ searchValue }}</span>
						{{ deptName.substr(deptName.indexOf(searchValue) + searchValue.length) }}
					</span>
					<span v-else>{{ deptName }}</span>
				</template>
			</a-tree>
		</a-spin>
	</globalModal>
</template>

<script>
import { sysManageapi } from '@/api/index.js';
import { ModalMixins } from '@/mixins';
import { clearDeep } from '@/utils/base';
import { mapState, mapMutations } from 'vuex';
import { DEPTTYPE } from '@/utils/enumeration';
let dataList = [];
const getParentKey = (values, tree) => {
	let newtreee = [];
	for (let i = 0; i < tree.length; i++) {
		const node = tree[i];
		if (
			values.some(value => {
				return JSON.stringify(node).indexOf('"deptId":"' + value + '"') > -1;
			})
		) {
			let value = values.find(value => {
				return JSON.stringify(node).indexOf('"deptId":"' + value + '"') > -1;
			});
			if (node.deptId == value) {
				node.children = null;
			} else {
				node.children = getParentKey(values, node.children);
			}
			newtreee.push(node);
		}
	}
	return newtreee;
};
const generateList = data => {
	for (let i = 0; i < data.length; i++) {
		const node = data[i];
		const key = node.deptId;
		dataList.push({ key, title: node.deptName });
		if (node.children) {
			generateList(node.children);
		}
	}
};
export default {
	name: 'changeDeptModal',
	data() {
		return {
			title: '选择部门',
			deptId: '',
			orgId: '',
			deptInfo: '',
			deptList: [],
			treeData: [],
			alltreeData: [],
			treeKeys: [],
			autoExpandParent: false,
			expandedKeys: [],
			searchValue: '',
			selectDeptType: '', //选中的部门类型
			replaceFields: { children: 'children', title: 'deptName', key: 'deptId', value: 'deptId' },
			mode: 'default' //default 单选，multiple 多选
		};
	},
	mixins: [ModalMixins],
	created() {},
	computed: {
		...mapState(['allDeptTree'])
	},
	methods: {
		...mapMutations(['SET_ALLDEPTTREE']),
		show(orgId, mode) {
			this.treeKeys = [];
			this.deptList = [];
			this.deptInfo = undefined;
			this.mode = mode || 'default';
			this.orgId = orgId || '';
			this.visible = true;
			this.getDeptTree();
		},
		setDeptTree(alltree) {
			let tree = [...alltree];
			this.treeData = [...tree];
			this.alltreeData = [...tree];
			let expandedKeys = [],
				dataList = [];
			if (tree.length > 0) {
				tree.forEach(item => {
					expandedKeys.push(item.deptId);
				});
				generateList([...tree]);
			}
			this.expandedKeys = [...expandedKeys];
		},
		handleOk() {
			if (this.deptList.length > 0) {
				if (this.mode == 'default') {
					if (this.selectDeptType && this.deptInfo.deptType !== this.selectDeptType) {
						this.$message.info('请选择一个' + DEPTTYPE[this.selectDeptType] + '部门');
						return false;
					}
					this.$emit('selectDept', this.deptInfo);
					this.visible = false;
				} else {
					if (this.selectDeptType && this.deptInfo.deptType !== this.selectDeptType) {
						this.$message.info('请选择一个' + DEPTTYPE[this.selectDeptType] + '部门');
						return false;
					}
					/* 多选部门，不能跨机构 */
					let orgId = this.deptList[0].orgId;
					if (!this.orgId && this.deptList.length > 1 && !this.deptList.every(item => item.orgId == orgId)) {
						this.$message.info('请选择同一机构下的部门');
					} else {
						this.$emit('selectDept', this.deptList);
						this.visible = false;
					}
				}
			} else {
				this.$message.info('请选择一个部门');
			}
		},
		handleCancel() {
			this.$emit('close');
			this.visible = false;
		},
		onExpand(expandedKeys) {
			this.expandedKeys = expandedKeys;
			this.autoExpandParent = false;
		},
		getDeptTree() {
			this.confirmLoading = true;
			this.$postAction(sysManageapi.deptUrl.getDeptList, {
				orgId: this.orgId
			})
				.then(res => {
					if (res && res.code == 1) {
						let alltree = [...res.data];
						this.setDeptTree(alltree);
						this.SET_ALLDEPTTREE(res.data);
					}
				})
				.finally(() => {
					this.confirmLoading = false;
				});
		},
		searchDept(e) {
			const value = e.target.value;
			if (value) {
				const expandedKeys = dataList
					.map(item => {
						if (item.title.indexOf(value) > -1) {
							return item.key;
						}
						return null;
					})
					.filter((item, i, self) => item && self.indexOf(item) === i);
				let list = JSON.parse(JSON.stringify(this.alltreeData));
				let newtree = getParentKey(expandedKeys, list);
				this.treeData = [...newtree];
				Object.assign(this, {
					expandedKeys,
					searchValue: value,
					autoExpandParent: true
				});
			} else {
				this.treeData = [...this.alltreeData];
				let expandedKeys = [];
				this.treeData.forEach(item => {
					expandedKeys.push(item.deptId);
				});
				Object.assign(this, {
					expandedKeys,
					searchValue: value,
					autoExpandParent: false
				});
			}
		},
		selectTree(selectedKeys, e) {
			this.deptInfo = selectedKeys && selectedKeys.length > 0 ? e.node.dataRef : undefined;
			if (this.mode == 'default') {
				this.deptList = [this.deptInfo];
			} else {
				if (selectedKeys && selectedKeys.length > this.deptList.length) {
					this.deptList.push(this.deptInfo);
				} else {
					this.deptList = this.deptList.filter(item => selectedKeys.includes(item.deptId));
				}
			}
		}
	}
};
</script>

<style scoped="scoped">
.icon {
	height: 12px;
	width: 12px;
	vertical-align: -0.125em;
}
</style>
